﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using SPWSWrapper;
using System.Security.Cryptography.X509Certificates;
using ULSLogParser;
using System.Collections;
using System.Windows.Forms.DataVisualization.Charting;
using SharePointManager.Properties;


namespace SharePointManager
{
    public partial class FrmMain : Form
    {
        #region Local Variables
        WebSP _spWSWR = new WebSP();
        bool _DataLoaded = false;
        Hashtable _LogTables = new Hashtable();
        Hashtable _LogTrees = new Hashtable();
        Hashtable _SharePointConnections = new Hashtable();
        #endregion
        #region Constants
        const string ULS_LOG_NODE_TITLE = "ULS Logs";
        #endregion
        public FrmMain()
        {
            InitializeComponent();
        }



        #region Icon Mapping Methods
        private int GetIconMapping(string ServerTemplate)
        {
            switch (ServerTemplate)
            {
                case "100":
                    return 6;
                case "101":
                    return 5;
                case "103":
                    return 8;
                case "106":
                    return 13;
                case "107":
                    return 10;
                case "109":
                    return 7;
                case "116":
                    return 5;
                case "302":
                    return 4;
                case "303":
                    return 3;

                default:
                    return 6;
            }
        }
        private int GetIconMappingForFile(string ServerTemplate)
        {
            switch (ServerTemplate.ToLower())
            {
                case "xls":
                case "xlsx":
                case "csv":
                    return 20;
                case "doc":
                case "docx":
                case "rtf":
                    return 15;
                case "ppt":
                case "pptx":
                    return 23;
                case "master":
                    return 18;
                case "aspx":
                case "asp":
                case "html":
                case "htm":
                    return 17;
                case "zip":
                case "cab":
                case "rar":
                    return 24;
                case "vsd":
                case "vsdx":
                    return 32;
                case "folder":
                    return 33;
                default:
                    return 16;
            }
        }
        private int GetIconMappingForObject(string CatText)
        {
            switch (CatText.Trim().ToLower())
            {
                case "critical":
                    return 27;

                case "high":
                case "medium":
                case "low":
                    return 25;
                case "monitorable":
                case "unexpected":
                    return 30;
                case "information":
                    return 28;
                case "warning":
                    return 29;
                case "exception":
                    return 30;
                default:
                    return 16;
            }
        }
        #endregion
        #region SharePoint Data Methods
        #region File Manipulation Methodes
        private void OpenFile(string URL, string FileName, string FileType)
        {
            //Downlaod the file
            byte[] fileContents = _spWSWR.DownloadFile(URL);
            MemoryStream stream = null;

            try
            {
                stream = new MemoryStream(fileContents);
            }
            catch
            {
                stream.Close();
                throw;
            }
            switch (FileType.ToLower())
            {
                case "asp":
                case "aspx":
                case "txt":
                case "master":
                case "htm":
                case "html":
                case "css":
                case "js":
                case "vb":
                case "cs":
                    {
                        StreamReader reader = null;
                        try
                        {
                            reader = new StreamReader(stream);
                            string FileContent = reader.ReadToEnd();
                            tabMain.SelectedTab = CreateNewPreviewTab(FileName, URL, FileContent);
                            reader.Close();
                        }
                        catch
                        {
                            reader.Close();
                            throw;
                        }
                        break;
                    }
                default:
                    break;
            }
            if (stream != null)
                stream.Close();
        }
        private void DownloadFile(string URL, string FileName, string FileExtension)
        {

            //Receive a Document Contents  into Byte array (filecontents)
            byte[] fileContents = null;
            string FileReadingError = "Error occured while downloading file!. \n The file is deleted or may not exist.";
            try
            {
                fileContents = _spWSWR.DownloadFile(URL);
            }
            catch (Exception Ex)
            {
                FileReadingError = ErrorHandler.GetFriendlyErrorMessage(Ex.Message);
            }


            if (fileContents != null)
            {
                saveFileDialogMain.FileName = FileName;
                saveFileDialogMain.DefaultExt = FileExtension;
                saveFileDialogMain.Filter = FileExtension.ToUpper() +
                                            " files |*." + FileExtension + "|All files (*.*)|*.*";
                if (saveFileDialogMain.ShowDialog() == DialogResult.OK)
                {
                    //Create a new file and write contents to that document
                    FileStream fStream = new FileStream(saveFileDialogMain.FileName, FileMode.Create, FileAccess.ReadWrite);
                    fStream.Write(fileContents, 0, fileContents.Length);
                    fStream.Close();
                }
            }
            else
                MessageBox.Show(FileReadingError,
                               "Error downloading file", MessageBoxButtons.OK, MessageBoxIcon.Error);


        }
        private void DownloadFile(string URL, string FileName)
        {

            //Receive a Document Contents  into Byte array (filecontents)
            byte[] fileContents = _spWSWR.DownloadFile(URL);

            if (fileContents != null)
            {

                //Create a new file and write contents to that document
                FileStream fStream = new FileStream(FileName, FileMode.Create, FileAccess.ReadWrite);
                fStream.Write(fileContents, 0, fileContents.Length);
                fStream.Close();

            }


        }
        #endregion
        #region Sites and Lists Methodes
        private void FillSiteData(TreeNode Root, string SiteUrl)
        {
            //Prepare ws settings
            _spWSWR.WebUrl = SiteUrl;
            DataTable SubSites = null;
            DataTable ListsData = null;
            string SubSitesErrorText = "";
            string ListsDataErrorText = "";
            try
            {
                SubSites = _spWSWR.GetSubSitesWithProperties(SiteUrl);
            }
            catch (Exception Ex)
            {

                MessageBox.Show("Error occured while getting SharePoint subsites data!. Error details \n" + Ex.Message,
                                "Error getting subsite data", MessageBoxButtons.OK, MessageBoxIcon.Error);
                SubSitesErrorText = Ex.Message;
            }

            try
            {
                ListsData = _spWSWR.GetLists();
            }
            catch (Exception Ex)
            {

                MessageBox.Show("Error occured while getting site lists data!. Error details \n" + Ex.Message,
                                "Error getting list data", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ListsDataErrorText = Ex.Message;
            }

            TreeNode SubSitesNode = Root.Nodes.Add("Sub Sites");
            SubSitesNode.ImageIndex = 12;

            TreeNode ListsTreeNode = Root.Nodes.Add("Lists");
            ListsTreeNode.ImageIndex = 6;

            //Fill the sub sites nodes
            if (SubSites != null)
            {
                foreach (DataRow site in SubSites.Rows)
                {
                    //Add the list to the tree
                    TreeNode newNode = new TreeNode(site["Title"].ToString());
                    newNode.Tag = site;
                    newNode.ImageIndex = 12;
                    SubSitesNode.Nodes.Add(newNode);
                }
            }
            else
            {
                SubSitesNode.Name += " (Unable to Read!)";
                SubSitesNode.ToolTipText = SubSitesErrorText;
            }

            //Fill the lists nodes
            if (ListsData != null)
            {
                foreach (DataRow list in ListsData.Rows)
                {
                    //Add the list to the tree
                    TreeNode newNode = new TreeNode(list["Title"].ToString());
                    newNode.Tag = list;
                    newNode.ImageIndex = GetIconMapping(list["ServerTemplate"].ToString());
                    ListsTreeNode.Nodes.Add(newNode);
                    //Add a sub node for items
                    TreeNode itemListNode = newNode.Nodes.Add("Items");
                    itemListNode.Tag = new DataTable("ListItems");
                    itemListNode.ImageIndex = 19;
                }
            }
            else
            {
                ListsTreeNode.Name += " (Unable to Read!)";
                ListsTreeNode.ToolTipText = ListsDataErrorText;
            }
        }
        private void LoadSite(bool Clear, string SiteUrl, TreeNode SiteNode, bool RootSite, bool TopLevelSite)
        {
           
            DataTable SubSites = null;
            DataTable ListsData = null;
            DataTable SiteMetaData = null;
            DataTable SubSiteData = null;
            DataTable Permissions = null;
            DataTable Groups = null;
            DataTable Users = null;
            bool InheritedSecurity = false;

            string SubSitesError = "";

            //Load the site meta data node
            try
            {
                SiteMetaData = _spWSWR.GetWebMetaData(SiteUrl, out Permissions, out Groups, out Users, out SubSiteData, TopLevelSite);
                if (SiteMetaData != null &&
                    SiteMetaData.Columns.Contains("InheritedSecurity"))
                    InheritedSecurity = SiteMetaData.Rows[0]["InheritedSecurity"].ToString() == "True";
            }
            catch (Exception Ex)
            {

                MessageBox.Show("Error occured while connecting to SharePoint site!. Error details \n" + Ex.Message,
                                "Error connecting to SharePoint", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            //Load the sub sites nodes
            try
            {
                SubSites = _spWSWR.GetSubSitesWithProperties(SiteUrl);
                //Add extra meta data 
                SubSites.Merge(SubSiteData, false, MissingSchemaAction.Add);
            }
            catch (Exception Ex)
            {

                MessageBox.Show("Error occured while getting SharePoint subsites data!. Error details \n" + Ex.Message,
                                "Error getting subsite data", MessageBoxButtons.OK, MessageBoxIcon.Error);
                SubSitesError = Ex.Message;
            }

            //Load the lists node
            try
            {
                ListsData = _spWSWR.GetLists();
            }
            catch (Exception Ex)
            {

                MessageBox.Show("Error occured while getting site lists data!. Error details \n" + Ex.Message,
                                "Error getting list data", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            //Add the root node
            if (SiteMetaData != null && SiteMetaData.Rows.Count > 0)
            {
                if (Clear)
                {
                    //TODO: Create a loop that goes over all TreeNodes and Dispose all objects
                    // Referenced in the Node Tags
                    SiteNode.Nodes.Clear();
                    lsvLists.Items.Clear();

                }

                if (RootSite)
                {
                    SiteNode.Text = SiteMetaData.Rows[0]["Title"].ToString();
                    //RootSiteNode.Tag = RootSite.Rows[0];
                    SiteNode.Tag = SiteMetaData.Rows[0];
                    SiteNode.ImageIndex = 21;
                }
                else
                {
                    //Append metadata to site
                    ((DataRow)SiteNode.Tag).Table.Merge(SiteMetaData);
                }
                TreeNode PermissionsNode = SiteNode.Nodes.Add("Roles");
                PermissionsNode.ImageIndex = 38;

                TreeNode GroupsNode = SiteNode.Nodes.Add("Groups");
                GroupsNode.ImageIndex = 34;

                TreeNode UsersNode = SiteNode.Nodes.Add("Users");
                UsersNode.ImageIndex = 35;

                TreeNode SubSitesNode = SiteNode.Nodes.Add("Sub Sites");
                SubSitesNode.ImageIndex = 12;
                SubSitesNode.Name = "SubSites";

                TreeNode ListsTreeNode = SiteNode.Nodes.Add("Lists");
                ListsTreeNode.ImageIndex = 6;

                //Fill Permissions
                foreach (DataRow perm in Permissions.Rows)
                {
                    TreeNode newNode = new TreeNode(perm["Name"].ToString());
                    newNode.Tag = perm;
                    newNode.ImageIndex = 38;
                    PermissionsNode.Nodes.Add(newNode);
                }
                if (InheritedSecurity)
                {
                    GroupsNode.Text += " [Inherited]";
                    UsersNode.Text += " [Inherited]";
                }
                else
                {
                    //Fill Groups
                    foreach (DataRow group in Groups.Rows)
                    {
                        TreeNode newNode = new TreeNode(group["Name"].ToString());
                        newNode.Tag = group;
                        newNode.ImageIndex = 36;
                        GroupsNode.Nodes.Add(newNode);
                    }

                    //Fill Users
                    foreach (DataRow user in Users.Rows)
                    {
                        TreeNode newNode = new TreeNode(user["Name"].ToString());
                        newNode.Tag = user;
                        newNode.ImageIndex = 37;
                        UsersNode.Nodes.Add(newNode);
                    }
                }
                //Fill the sub sites nodes
                if (SubSites != null)
                {
                    foreach (DataRow site in SubSites.Rows)
                    {
                        //Add the list to the tree
                        TreeNode newNode = new TreeNode(site["Title"].ToString());
                        newNode.Tag = site;
                        newNode.ImageIndex = 12;
                        SubSitesNode.Nodes.Add(newNode);
                    }
                }
                else
                {
                    SubSitesNode.Text += "[Error]";
                    SubSitesNode.ToolTipText = SubSitesError;
                }
                if (ListsData != null)
                {
                    //Fill the lists nodes
                    foreach (DataRow list in ListsData.Rows)
                    {
                        //Add the list to the tree
                        TreeNode newNode = new TreeNode(list["Title"].ToString());
                        newNode.Tag = list;
                        newNode.ImageIndex = GetIconMapping(list["ServerTemplate"].ToString());
                        ListsTreeNode.Nodes.Add(newNode);
                        //Add a sub node for items
                        TreeNode itemListNode = newNode.Nodes.Add("Items");
                        itemListNode.Tag = new DataTable("ListItems");
                        itemListNode.ImageIndex = 19;

                        //Add a sub node for columns
                        TreeNode itemFieldNode = newNode.Nodes.Add("Fields");
                        itemFieldNode.Tag = new DataTable("Fields");
                        itemFieldNode.ImageIndex = 19;
                        string ListID = list["ID"].ToString();

                        //Get List Fields data
                        DataTable ListFields = null;
                        string ErrorMessage = "";
                        try
                        {
                            ListFields = _spWSWR.GetListFieldsData(ListID);
                        }
                        catch (Exception Ex)
                        {
                            ListFields = new DataTable("[Error]");
                            ErrorMessage = Ex.Message;
                        }
                        if (ListFields.Rows.Count <= 0)
                        {
                            itemFieldNode.Text += " [Error]"; itemFieldNode.ToolTipText = ErrorMessage;
                        }
                        else
                        {
                            foreach (DataRow Lfield in ListFields.Rows)
                            {

                                TreeNode TempFieldNode = itemFieldNode.Nodes.Add(Lfield["Title"].ToString());
                                TempFieldNode.Tag = Lfield;
                                TempFieldNode.ImageIndex = 19;
                            }
                        }


                    }
                }
              
            }
        }
        private void LoadData(bool Clear)
        {
            //Prepare ws credentials
            if (checkBoxUseDefaultCredentials.Checked)
                _spWSWR.Initialize(comboBoxSiteUrl.Text);
            else
                _spWSWR.Initialize(txtUserName.Text, txtPassword.Text, txtDomain.Text, comboBoxSiteUrl.Text);



            //Add the root node
            TreeNode RootSiteNode = new TreeNode();
            if (Clear)
            {
                //TODO: Create a loop that goes over all TreeNodes and Dispose all objects
                // Referenced in the Node Tags
                trvLists.Nodes.Clear();
                _DataLoaded = false;
                dgvItems.DataSource = null;
                lsvLists.Items.Clear();
            }
            trvLists.Nodes.Add(RootSiteNode);

            LoadSite(false, _spWSWR.WebUrl, RootSiteNode, true, true);

            if (trvLists.Nodes.Count > 0)
                _DataLoaded = true;

        }
        private XmlNode GetListData(string ListUniqueIdentifier, string webUrl)
        {
            WSDspSts.StsAdapter ListsDataService = new WSDspSts.StsAdapter();
            ListsDataService.Url = webUrl + "/_vti_bin/DspSts.asmx";
            ListsDataService.Credentials = new NetworkCredential(txtUserName.Text, txtPassword.Text, txtDomain.Text);

            string[] vArray = new string[1];
            vArray[0] = "1.0";
            WSDspSts.Versions myVersion = new WSDspSts.Versions();
            myVersion.version = vArray;

            ListsDataService.versions = myVersion;

            WSDspSts.RequestHeader reqHeader = new WSDspSts.RequestHeader();
            reqHeader.document = WSDspSts.DocumentType.content;
            reqHeader.method = WSDspSts.MethodType.query;

            ListsDataService.request = reqHeader;

            WSDspSts.QueryRequest myRequest = new WSDspSts.QueryRequest();

            WSDspSts.DSQuery sQuery = new WSDspSts.DSQuery();
            sQuery.select = string.Format("/list[@id='{0}']", ListUniqueIdentifier);

            myRequest.dsQuery = sQuery;

            WSDspSts.DspQuery spQuery = new WSDspSts.DspQuery();
            XmlDocument xmlDoc = new System.Xml.XmlDocument();
            XmlElement ndQuery = xmlDoc.CreateElement("And");
            ndQuery.InnerXml = "";
            //spQuery.Where = ndQuery;

            myRequest.dsQuery.Query = spQuery;
            return ListsDataService.Query(myRequest);


        }
        #endregion
        #endregion
        private bool ExitApplicationAndSave()
        {
            if (MessageBox.Show("Are you sure you want to exist the SharePoint Manager?", "SharePoint Manager - Exit Application", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == System.Windows.Forms.DialogResult.OK)
            {
                //Save User settings
                try
                {
                    if (!string.IsNullOrEmpty(comboBoxSiteUrl.Text.Trim()))
                    {
                        //Check if the user wants to save credentials
                        if (checkBoxRememberCredentials.Checked)
                        {
                            AddorUpdateSharePointConnection(comboBoxSiteUrl.Text, txtUserName.Text, txtPassword.Text, txtDomain.Text, checkBoxUseDefaultCredentials.Checked);
                        }
                        else
                            AddorUpdateSharePointConnection(comboBoxSiteUrl.Text, "", "", "", checkBoxUseDefaultCredentials.Checked);
                    }
                }
                catch (Exception Ex)
                {
                    MessageBox.Show("Error saving used connections. Error Details:\n\n"+Ex.Message, "SharePoint Manager - Exit Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
            
                }
                
                return true;
            }
            return false;
        }
        private DataRow GetSavedSharePointConnection(string SharePointUrl)
        {
            DataTable CurrentConnectionStr = Settings.Default.SharePointConnection;
            if (CurrentConnectionStr != null)
            {
                //Find the connection string
                foreach (DataRow connection in CurrentConnectionStr.Rows)
                {
                    if (string.Compare(SharePointUrl, connection["Url"].ToString(), true) == 0)
                    {
                        return connection;
                    }
                }
            }
            return null;
        }
        private void AddorUpdateSharePointConnection(string SharePointUrl, string UserName, string Password, string Domain, bool Trusted)
        {
            DataTable CurrentConnectionStr = Settings.Default.SharePointConnection;
            bool NewRecord = false;
            if (CurrentConnectionStr == null)
            {
                //if the table never existed before. 
                CurrentConnectionStr = new DataTable("ConnectionStr");
            }
                //Ensure columns exist - Build the schema of the table
                if(!CurrentConnectionStr.Columns.Contains("Url"))
                    CurrentConnectionStr.Columns.Add("Url");
                DataColumn PK = CurrentConnectionStr.Columns["Url"];
                if (!CurrentConnectionStr.Columns.Contains("UserName"))
                    CurrentConnectionStr.Columns.Add("UserName");
                if (!CurrentConnectionStr.Columns.Contains("Password"))
                    CurrentConnectionStr.Columns.Add("Password");
                if (!CurrentConnectionStr.Columns.Contains("Domain"))
                    CurrentConnectionStr.Columns.Add("Domain");
                if (!CurrentConnectionStr.Columns.Contains("Trusted"))
                    CurrentConnectionStr.Columns.Add("Trusted");
                if (!CurrentConnectionStr.Columns.Contains("SaveConnection"))
                    CurrentConnectionStr.Columns.Add("SaveConnection");
                if(CurrentConnectionStr.PrimaryKey == null)
                CurrentConnectionStr.PrimaryKey = new DataColumn[] { PK };
            
            //Find the connection string
            DataRow ConnectionString = null;
            foreach (DataRow connection in CurrentConnectionStr.Rows)
            {
                if(string.Compare(SharePointUrl,connection["Url"].ToString(),true) == 0)
                {
                    ConnectionString = connection;
                    break;
                }
            }
            if(ConnectionString ==null)
            {
                ConnectionString = CurrentConnectionStr.NewRow();
                NewRecord = true;
            }
            ConnectionString["Url"] = SharePointUrl;

            if(Trusted)
            {
                ConnectionString["UserName"] = "";
                ConnectionString["Password"] = "";
                ConnectionString["Domain"] = "";
                ConnectionString["Trusted"] = "True";
            }
            else
            {
                ConnectionString["UserName"] = string.IsNullOrEmpty(UserName)?"" : Security.EncryptStringAES(UserName, Security.GetUniqueKey());
                //Encrypt password
                string PWEnc = "";
                if(!string.IsNullOrEmpty(Password))
                    PWEnc = Security.EncryptStringAES(Password, Security.GetUniqueKey());
                ConnectionString["Password"] = PWEnc;
                ConnectionString["Domain"] = string.IsNullOrEmpty(Domain) ? "" : Security.EncryptStringAES(Domain, Security.GetUniqueKey());
                ConnectionString["Trusted"] = "False";
            }
            if(NewRecord)
                CurrentConnectionStr.Rows.Add(ConnectionString);
            Settings.Default.SharePointConnection = CurrentConnectionStr;
            Settings.Default.LastUsedConnection = SharePointUrl;
            Settings.Default.Save();   
        }
        private void LoadRecentConnections()
        {
            DataTable Connections = Settings.Default.SharePointConnection;
            if (Connections != null)
            {
                comboBoxSiteUrl.DataSource = Connections;
                comboBoxSiteUrl.DisplayMember = "Url";
                comboBoxSiteUrl.ValueMember = "Url";
                comboBoxSiteUrl_SelectionChangeCommitted(this, null);
            }
        }
        private void btnLoadLists_Click(object sender, EventArgs e)
        {
            //Call this before you try to load a web service over ssl with an invalid certificate
            System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
            //Check if the data is already loaded
            if (_DataLoaded)
            {
                if (MessageBox.Show("SharePoint site data is already loaded! This will reload all the data again.\nDo you want to continue?",
                               "Data is already loaded", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
                {
                    trvLists.Nodes.Clear();
                    LoadData(true);
                }
            }
            else
                LoadData(false);

        }
        private void button1_Click(object sender, EventArgs e)
        {
            /*
            //Copy WebService Settings
            string webUrl = txtSiteUrl.Text;
            WSCopy.Copy copyService = new WSCopy.Copy();
            copyService.Url = webUrl + "/_vti_bin/copy.asmx";
            copyService.Credentials = new NetworkCredential(txtUserName.Text, txtPassword.Text, txtDomain.Text);

            //Source and Destination Document URLs
            string sourceUrl = txtFileUrl.Text;//"http://w2k3_moss/_catalogs/masterpage/default.master";
            //string destinationUrl = "C:\\Sample.doc";

            //Variables for Reading metadata’s of a document
            WSCopy.FieldInformation fieldInfo = new WSCopy.FieldInformation();
            WSCopy.FieldInformation[] fieldInfoArray = { fieldInfo };
            WSCopy.CopyResult cResult1 = new WSCopy.CopyResult();
            WSCopy.CopyResult cResult2 = new WSCopy.CopyResult();
            WSCopy.CopyResult[] cResultArray = { cResult1, cResult2 };

            //Receive a Document Contents  into Byte array (filecontents)
            byte[] fileContents = new Byte[4096];
            copyService.GetItem(sourceUrl, out fieldInfoArray, out fileContents);
            if(fileContents != null)
            {
                if (saveFileDialogMain.ShowDialog() == DialogResult.OK)
                {
                    //Create a new file and write contents to that document
                    FileStream fStream = null;
                    try
                    {
                        fStream = new FileStream(saveFileDialogMain.FileName, FileMode.Create, FileAccess.ReadWrite);
                        fStream.Write(fileContents, 0, fileContents.Length);
                        fStream.Close();
                    }
                    catch
                    {
                        fStream.Close();
                        throw;
                    }
                  
                        
                }
            }
            
            */
        }
        private void lsvLists_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            toolStripStatusLabelSelectedNodesCount.Text = "Selected: " + lsvLists.SelectedItems.Count.ToString();

        }
        private void LoadListItemsIntoTree(TreeNode TargetNode)
        {
            //Load items of a list
            DataTable SelectedListItem = (DataTable)TargetNode.Tag;


            if (SelectedListItem.TableName == "ListItems")
            {
                if (SelectedListItem.Rows.Count <= 0)
                {
                    //Get Quick Filters
                    string IDFilterFrom = "";
                    string IDFilterTo = "";
                    string QuickFilterStr = GetListQuickFilter(TargetNode);
                    if (!string.IsNullOrEmpty(QuickFilterStr))
                    {
                        //Parse Filter
                        string[] QuickFilters = QuickFilterStr.Split(',');
                        foreach (string filter in QuickFilters)
                        {
                            if (filter.StartsWith("Id:"))
                            {
                                string[] FilterParams = filter.Replace("Id:", "").Split(':');
                                IDFilterFrom = FilterParams[0];
                                IDFilterTo = FilterParams[1];

                            }
                        }
                    }
                    DataRow SelectedList = (DataRow)TargetNode.Parent.Tag;
                    DataTable Result = null;
                    try
                    {
                        if (!string.IsNullOrEmpty(IDFilterFrom) && !string.IsNullOrEmpty(IDFilterTo))
                            Result = _spWSWR.GetListData(SelectedList["ID"].ToString(), IDFilterFrom, IDFilterTo);
                        else
                            Result = _spWSWR.GetListData(SelectedList["ID"].ToString());

                    }
                    catch (Exception Ex)
                    {
                        //TODO: Make this show as an error message with icons and everything
                        MessageBox.Show(ErrorHandler.GetFriendlyErrorMessage(Ex.Message));
                        return;
                    }
                    //Add the appropriate icon
                    foreach (DataRow item in Result.Rows)
                    {
                        if (Result.Columns.Contains("File Type") && item["File Type"] != null &&
                            !string.IsNullOrEmpty(item["File Type"].ToString()))
                            item["  "] = imlMain.Images[GetIconMappingForFile(item["File Type"].ToString())];
                        else if (Result.Columns.Contains("  "))
                            item["  "] = imlMain.Images[19];
                    }
                    TargetNode.Tag = Result;
                    dgvItems.DataSource = Result;
                    tabMain.SelectedIndex = 1;
                }
                else//Fill Items Page from memory
                {
                    dgvItems.DataSource = TargetNode.Tag;
                    tabMain.SelectedIndex = 1;
                }

            }
        }
        private void trvLists_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Tag == null) return;
            if (e.Node.Tag.GetType() == typeof(DataRow))
            {
                //Load properties page
                DataRow SelectedList = (DataRow)e.Node.Tag;
                LoadPropertiesPage(SelectedList);
            }
            else if (e.Node.Tag.GetType() == typeof(DataTable))
            {
                switch (e.Node.Text)
                {
                    case "Items":
                        //Load items of a list
                        LoadListItemsIntoTree(e.Node);
                        break;
                    case "Fields":
                        //LoadListFieldsIntoTree(e.Node);
                        break;
                    default:
                        break;
                }

            }


        }
        private void LoadPropertiesPage(DataRow SelectedList)
        {
            //Load properties page
            lsvLists.Items.Clear();

            foreach (DataColumn Col in SelectedList.Table.Columns)
            {
                lsvLists.Items.Add(Col.Caption).SubItems.Add(SelectedList[Col.Caption].ToString());
            }
            lsvLists.Sorting = SortOrder.Ascending;
            lsvLists.Sort();
            tabMain.SelectedIndex = 0;
        }

        //private void LoadListFieldsIntoTree(TreeNode TargetNode)
        //{
        //    //Load list fields data
        //    DataTable SelectedListItem = (DataTable)TargetNode.Tag;


        //    if (SelectedListItem.TableName == "ListFields")
        //    {
        //        if (SelectedListItem.Rows.Count <= 0)
        //        {
        //            vvvvvvvvvvvvvvvvvv
        //            DataRow SelectedList = (DataRow)TargetNode.Parent.Tag;
        //            DataTable Result = null;
        //            try
        //            {
        //                    Result = _spWSWR.GetListData(SelectedList["ID"].ToString());

        //            }
        //            catch (Exception Ex)
        //            {
        //                //TODO: Make this show as an error message with icons and everything
        //                MessageBox.Show(ErrorHandler.GetFriendlyErrorMessage(Ex.Message));
        //                return;
        //            }

        //            TargetNode.Tag = Result;
        //            dgvItems.DataSource = Result;
        //            tabMain.SelectedIndex = 0;
        //        }
        //        else//Fill Fields Page from memory
        //        {
        //            dgvItems.DataSource = TargetNode.Tag;
        //            tabMain.SelectedIndex = 0;
        //        }

        //    }
        //}
        private void trvLists_DoubleClick(object sender, EventArgs e)
        {
            if (trvLists.SelectedNode == null) return;

            TreeNode SelectedNode = trvLists.SelectedNode;
            if (SelectedNode.Nodes.Count <= 0)
            {
                if (SelectedNode.Tag != null && SelectedNode.Tag.GetType() == typeof(DataRow))
                {
                    DataRow NodeData = SelectedNode.Tag as DataRow;
                    if (NodeData.Table.TableName == "Sites")
                    {
                        //FillSiteData(SelectedNode, NodeData["Url"].ToString());
                        LoadSite(false, NodeData["Url"].ToString(), SelectedNode, false,false);
                        //Reload Properties
                        LoadPropertiesPage(NodeData);
                    }
                }
            }
        }
        private void button1_Click_1(object sender, EventArgs e)
        {
            WebSP spWSWR = new WebSP(txtUserName.Text, txtPassword.Text, txtDomain.Text, comboBoxSiteUrl.Text);
            spWSWR.GetLists();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //load the recently used SharePoint connections
            try
            {
                LoadRecentConnections();
            }
            catch (Exception Ex)
            {
                MessageBox.Show("Error saving connections. Error: " + Ex.Message);
            }
        }
        private void contextMenuItems_Opened(object sender, EventArgs e)
        {
            //Check if a file is selected to enable file fucntions
            int RecordsCount = dgvItems.SelectedRows.Count;
            if (RecordsCount > 0)
            {
                if (dgvItems.SelectedRows[0].DataBoundItem.GetType() == typeof(DataRowView))
                {
                    DataRowView ItemDataRow = dgvItems.SelectedRows[0].DataBoundItem as DataRowView;

                    if (ItemDataRow.DataView.Table.Columns.Contains("File Type") &&
                        ItemDataRow["File Type"] != null &&
                        !string.IsNullOrEmpty(ItemDataRow["File Type"].ToString()) &&
                        ItemDataRow["File Type"].ToString().ToLower() != "folder")
                    {
                        toolStripMenuItemDownloadItem.Enabled = true;
                        openToolStripMenuItem.Enabled = true;
                    }
                    else
                    {
                        toolStripMenuItemDownloadItem.Enabled = false;
                        openToolStripMenuItem.Enabled = false;
                    }
                }
                else
                {
                    toolStripMenuItemDownloadItem.Enabled = false;
                    openToolStripMenuItem.Enabled = false;
                }
            }
            else
            {
                toolStripMenuItemDownloadItem.Enabled = false;
                openToolStripMenuItem.Enabled = false;
            }
        }
        private void toolStripMenuItemDownloadItem_Click(object sender, EventArgs e)
        {
            int RecordsCount = dgvItems.SelectedRows.Count;
            if (RecordsCount > 0)
            {
                if (dgvItems.SelectedRows[0].DataBoundItem.GetType() == typeof(DataRowView))
                {
                    DataRowView ItemDataRow = dgvItems.SelectedRows[0].DataBoundItem as DataRowView;

                    if (ItemDataRow["File Type"] != null && !string.IsNullOrEmpty(ItemDataRow["File Type"].ToString()))
                    {
                        //Check how many files are selected
                        if (RecordsCount == 1)
                            DownloadFile(ItemDataRow["FileRef"].ToString(),
                                         ItemDataRow["FileLeafRef"].ToString(),
                                         ItemDataRow["File Type"].ToString());
                        else
                        {
                            if (folderBrowserDialogMain.ShowDialog() == DialogResult.OK)
                            {
                                foreach (DataGridViewRow itemDataRow in dgvItems.SelectedRows)
                                {
                                    if (ItemDataRow["FileRef"] == null ||
                                       ItemDataRow["FileLeafRef"] == null ||
                                       string.IsNullOrEmpty(ItemDataRow["File Type"].ToString()))
                                        continue;
                                    ItemDataRow = itemDataRow.DataBoundItem as DataRowView;

                                    DownloadFile(ItemDataRow["FileRef"].ToString(),
                                                 folderBrowserDialogMain.SelectedPath + "\\" + ItemDataRow["FileLeafRef"].ToString());

                                }
                            }
                        }
                    }

                }

            }

        }

        private TabPage CreateNewPreviewTab(string Title, string FileName, string PreviewText)
        {
            // 
            // Create new TextBox
            //
            TextBox newTextBox = new TextBox();
            newTextBox.BackColor = System.Drawing.Color.White;
            newTextBox.Dock = System.Windows.Forms.DockStyle.Fill;
            newTextBox.Location = new System.Drawing.Point(3, 3);
            newTextBox.Multiline = true;
            newTextBox.Name = "txtPreview" + (tabMain.TabPages.Count + 1).ToString();
            newTextBox.ReadOnly = true;
            newTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            newTextBox.Size = new System.Drawing.Size(549, 679);
            newTextBox.TabIndex = 0;
            newTextBox.WordWrap = false;
            newTextBox.Text = PreviewText;
            // 
            // Add new TabPage
            //
            TabPage newTabPage = new TabPage();
            newTabPage.Controls.Add(newTextBox);
            newTabPage.Location = new System.Drawing.Point(4, 29);
            newTabPage.Name = "tabPageViewFile" + (tabMain.TabPages.Count + 1).ToString();
            newTabPage.Padding = new System.Windows.Forms.Padding(3);
            newTabPage.Size = new System.Drawing.Size(555, 685);
            newTabPage.TabIndex = 2;
            newTabPage.Text = Title;
            newTabPage.ToolTipText = FileName;
            newTabPage.Tag = FileName;
            newTabPage.UseVisualStyleBackColor = true;
            tabMain.TabPages.Add(newTabPage);
            return newTabPage;
        }
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int RecordsCount = dgvItems.SelectedRows.Count;
            if (RecordsCount > 0)
            {
                if (dgvItems.SelectedRows[0].DataBoundItem.GetType() == typeof(DataRowView))
                {
                    DataRowView ItemDataRow = dgvItems.SelectedRows[0].DataBoundItem as DataRowView;

                    if (ItemDataRow["File Type"] != null && !string.IsNullOrEmpty(ItemDataRow["File Type"].ToString()))
                    {

                        foreach (DataGridViewRow itemDataRow in dgvItems.SelectedRows)
                        {
                            if (ItemDataRow["FileRef"] == null ||
                               ItemDataRow["FileLeafRef"] == null ||
                               string.IsNullOrEmpty(ItemDataRow["File Type"].ToString()))
                                continue;
                            ItemDataRow = itemDataRow.DataBoundItem as DataRowView;

                            OpenFile(ItemDataRow["FileRef"].ToString(),
                                          ItemDataRow["FileLeafRef"].ToString(),
                                          ItemDataRow["File Type"].ToString());


                        }
                    }

                }

            }

        }
        private void lsvLists_DoubleClick(object sender, EventArgs e)
        {
            if (lsvLists.SelectedItems.Count > 0)
            {
                string Message = lsvLists.SelectedItems[0].SubItems[1].Text;
                Message = Message.Trim();
                Clipboard.SetDataObject(Message);
                OpenNewMessageWindow(Message);
            }

        }
        private void OpenNewMessageWindow(string Message)
        {
            Microscope NewMessageWindow = new Microscope();
            NewMessageWindow.textBoxMessage.Text = Message;
            NewMessageWindow.Show();
        }
        private void OpenNewVisualizerWindow(string Message, TreeNode DataNode)
        {
            Visualizer NewVisualizerWindow = new Visualizer();
            foreach (TreeNode item in DataNode.Nodes)
            {
                if (item.Tag != null &&
                    item.Tag.GetType() == typeof(DataRow))
                {
                    DataRow LogRecord = item.Tag as DataRow;
                    string TimeStampStr = LogRecord[Parser.COL_TIME_STAMP].ToString();
                    DateTime TimeStamp = DateTime.Parse(TimeStampStr);
                    long DTValue = TimeStamp.ToFileTime();

                }
                DataPoint NewPoint = new DataPoint();
                NewPoint.Label = "LABLE";
                NewPoint.SetValueXY(10m, 10m);
                NewVisualizerWindow.chartMain.Series[0].Points.Add(NewPoint);
            }

            //NewVisualizerWindow.chartMain.Series[0].Points.Add(
            NewVisualizerWindow.Show();
        }
        private void UpdateCounters(TreeNode LogData)
        {
            //Update the nodes count in the status bar
            if (LogData.Nodes.Count > 0)
            {
                toolStripStatusLabelNodesCount.Text = "Total: " + LogData.Nodes.Count.ToString();
                exportLogsSummaryToolStripMenuItem.Enabled = true;
            }
        }
        private void loadFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialogMain.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //string Test = @"c:\delete me\MPLTTATIS101-20100720-1003.log";

                //Open the log file and start parsing the logs into a datatable
                //Check if the file is opened already
                DialogResult DResult = DialogResult.Ignore;
                int CurrentNodeIndex = -1;
                if (_LogTables.Contains(openFileDialogMain.FileName))
                {
                    DResult = MessageBox.Show("ULS og file is already loaded! Do you want to overwrite the existing summary for that file?",
                               "ULS log is already loaded", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
                }
                if (DResult != DialogResult.Cancel)
                {
                    string FileName = openFileDialogMain.FileName;
                    string SafeFileName = openFileDialogMain.SafeFileName;
                    if (DResult == System.Windows.Forms.DialogResult.No)
                    {
                        SafeFileName = Parser.IncreamentSafeFileName(SafeFileName);
                        FileName = FileName.Replace(openFileDialogMain.SafeFileName, SafeFileName);
                    }
                    else if (DResult == System.Windows.Forms.DialogResult.Yes)
                    {
                        DataTable CurrentDataTable = _LogTables[FileName] as DataTable;
                        TreeNode CurrentTreeNode = _LogTrees[FileName] as TreeNode;
                        if (CurrentDataTable == null)
                            throw new Exception("ERROR FINDING THE CURRENT TABLE");
                        if (CurrentTreeNode == null)
                            throw new Exception("ERROR FINDING THE LOG TREE");

                        //Update Objects in memory
                        _LogTables.Remove(FileName);
                        _LogTrees.Remove(FileName);

                        //Update the tree view with the new data

                        TreeNode CurrentTreeNodeUI = Parser.FindFirstNodeByNodeText(trvLists, openFileDialogMain.SafeFileName);
                        if (CurrentTreeNodeUI == null)
                            throw new Exception("ERROR FINDING THE LOG TREE");
                        CurrentNodeIndex = CurrentTreeNodeUI.Index;
                        trvLists.Nodes.Remove(CurrentTreeNode);
                    }
                    DataTable Data = Parser.OpenTabFile(openFileDialogMain.FileName, FileName);
                    Parser.ConnectLogs(Data);
                    _LogTables.Add(FileName, Data);
                    dgvItems.DataSource = Data;

                    TreeNode LogData = Parser.GenerateSummary(Data,
                                                              GetIconMappingForObject,
                                                              SafeFileName,
                                                              FileName);
                    _LogTrees.Add(FileName, LogData);
                    if (DResult == DialogResult.Yes)
                        AddULsLogsData(trvLists, LogData, CurrentNodeIndex);
                    else
                        AddULsLogsData(trvLists, LogData);
                    UpdateCounters(LogData);
                }

            }
        }
        private void AddULsLogsData(TreeView TargetTree, TreeNode Data)
        {
            if (Data == null || TargetTree == null) return;
            TreeNode ULSNode = Parser.FindFirstNodeByNodeText(TargetTree, ULS_LOG_NODE_TITLE);
            if (ULSNode == null)
            {
                ULSNode = new TreeNode(ULS_LOG_NODE_TITLE);
                TargetTree.Nodes.Add(ULSNode);
            }
            ULSNode.Nodes.Add(Data);
        }
        private void AddULsLogsData(TreeView TargetTree, TreeNode Data, int Index)
        {
            if (Data == null || TargetTree == null) return;
            TreeNode ULSNode = Parser.FindFirstNodeByNodeText(TargetTree, ULS_LOG_NODE_TITLE);
            if (ULSNode == null)
            {
                ULSNode = new TreeNode(ULS_LOG_NODE_TITLE);
                TargetTree.Nodes.Add(ULSNode);
            }
            ULSNode.Nodes.Insert(Index, Data);
        }

        private void lsvLists_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        private void dgvItems_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {

        }

        private void dgvItems_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            string Selection = string.Format("Rows: {0}, Columns: {1}, Cells:{2}", dgvItems.SelectedRows.Count,
                                                                                  dgvItems.SelectedColumns.Count,
                                                                                  dgvItems.SelectedCells.Count);
            toolStripStatusLabelSelectedNodesCount.Text = Selection;

        }

        private void exportLogsSummaryToolStripMenuItem_Click(object sender, EventArgs e)
        {




        }

        private void contextMenuTree_Opened(object sender, EventArgs e)
        {

        }

        private void applyAIMatchingToolStripMenuItem_Click(object sender, EventArgs e)
        {

            //Get the node filename
            if (trvLists.SelectedNode != null &&
               trvLists.SelectedNode.Tag == null &&
                trvLists.SelectedNode.ToolTipText != "")
            {
                string FileName = trvLists.SelectedNode.ToolTipText;
                string SafeFileName = trvLists.SelectedNode.Text;
                DataTable CurrentDataTable = _LogTables[FileName] as DataTable;
                TreeNode CurrentTreeNode = _LogTrees[FileName] as TreeNode;
                if (CurrentDataTable == null)
                    throw new Exception("ERROR FINDING THE CURRENT TABLE");
                //TreeNode CurrentTree = Parser.FindFirstTreeNodeByNodeName(CurrentTreeNode, FileName);
                if (CurrentTreeNode == null)
                    throw new Exception("ERROR FINDING THE LOG TREE");
                TreeNode LogData = Parser.GenerateSummaryAI(CurrentDataTable, GetIconMappingForObject, Convert.ToDecimal(toolStripComboBoxAImatchingErrorAllowance.Text.Replace("%", "")), SafeFileName, FileName);

                //Update Objects in memory
                _LogTables.Remove(FileName);
                _LogTrees.Remove(FileName);

                _LogTables.Add(FileName, CurrentDataTable);
                _LogTrees.Add(FileName, LogData);

                //Update the tree view with the new data
                int CurrentNodeIndex = CurrentTreeNode.Index;
                trvLists.Nodes.Remove(CurrentTreeNode);
                AddULsLogsData(trvLists, LogData, CurrentNodeIndex);
                UpdateCounters(LogData);
            }
        }

        private void exportLogSummaryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Get the log file node
            if (trvLists.SelectedNode != null &&
               trvLists.SelectedNode.Tag == null &&
                trvLists.SelectedNode.ToolTipText != "")
            {
                string FileName = trvLists.SelectedNode.ToolTipText;
                string SafeFileName = trvLists.SelectedNode.Text;
                //DataTable CurrentDataTable = _LogTables[FileName] as DataTable;
                TreeNode CurrentTreeNode = _LogTrees[FileName] as TreeNode;
                //if (CurrentDataTable == null)
                //    throw new Exception("ERROR FINDING THE CURRENT TABLE");
                //TreeNode CurrentTree = Parser.FindFirstTreeNodeByNodeName(CurrentTreeNode, "FileName");
                if (CurrentTreeNode == null)
                    throw new Exception("ERROR FINDING THE LOG TREE");

                //Set the default file name for the summary report the same as the original log file
                saveFileDialogMain.FileName = SafeFileName.Replace("log", "xml");
                if (saveFileDialogMain.ShowDialog() == DialogResult.OK)
                {
                    //Create a new file and write contents to that document
                    Parser.ExportSummary(CurrentTreeNode, saveFileDialogMain.FileName);


                }

            }
        }

        private void toolStripButtonFilter_Click(object sender, EventArgs e)
        {
            ListFilterBuilder newFilterWindow = new ListFilterBuilder();
            if (newFilterWindow.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                toolStripButtonFilter.Text = "Edit\\Remove Filter";
            }
        }

        private void contextMenuItems_Opening(object sender, CancelEventArgs e)
        {

        }
        private void EnableFilterMenu(bool Enable, string ButtonText)
        {
            quickFiltersToolStripMenuItem.Enabled = Enable;
            iDToolStripMenuItem.Enabled = Enable;
            iDToolStripMenuItem.Text = ButtonText;
        }
        private void EnableAIMenu(bool Enable)
        {
            logSummaryToolStripMenuItem.Enabled = Enable;
            applyAIMatchingToolStripMenuItem.Enabled = Enable;
            exportLogSummaryToolStripMenuItem.Enabled = Enable;
        }
        private void trvLists_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                TreeNode SelectedNode = e.Node;
                //Check if the seleted node is a log summary node
                if (SelectedNode != null &&
                  SelectedNode.Tag == null &&
                   SelectedNode.ToolTipText != "")
                {
                    EnableAIMenu(true);
                }
                else
                {
                    EnableAIMenu(false);
                }

                //Check if we the selected node is "Items" root node
                if (SelectedNode != null &&
                  SelectedNode.Tag != null &&
                   SelectedNode.Text.StartsWith("Items"))
                {

                    iDToolStripMenuItem.Tag = SelectedNode;
                    if (!string.IsNullOrEmpty(GetListQuickFilter(SelectedNode)))
                    {
                        EnableFilterMenu(true, "Edit\\Remove ID Filter");

                    }
                    else
                        EnableFilterMenu(true, "Add ID Filter");
                }
                else
                {
                    EnableFilterMenu(false, "Add ID Filter");
                }
            }
        }

        private void iDToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //if(iDToolStripMenuItem.Text == "Add ID Filter")
            QuickListFilter newQuickFilterWindow = new QuickListFilter();
            newQuickFilterWindow.comboBoxColumn.Text = "ID";
            TreeNode SelectedNode = iDToolStripMenuItem.Tag as TreeNode;
            if (SelectedNode == null) return; //TODO: Implement error Message

            string QuickFilterStr = GetListQuickFilter(SelectedNode);
            if (string.IsNullOrEmpty(QuickFilterStr))
            {
                //No filter has been assigned yet
                newQuickFilterWindow.buttonCancel.Enabled = true;
                newQuickFilterWindow.buttonCancel.Text = "Cancel";
            }
            else
            {
                string[] QuickFilters = QuickFilterStr.Split(',');
                foreach (string filter in QuickFilters)
                {
                    if (filter.StartsWith("Id:"))
                    {
                        string[] FilterParams = filter.Replace("Id:", "").Split(':');
                        newQuickFilterWindow.textBoxFrom.Text = FilterParams[0];
                        newQuickFilterWindow.textBoxTo.Text = FilterParams[1];

                    }
                }
                newQuickFilterWindow.buttonCancel.Enabled = true;
            }
            DialogResult Result = newQuickFilterWindow.ShowDialog();
            if (Result == System.Windows.Forms.DialogResult.OK)
            {
                string Filter = newQuickFilterWindow.comboBoxColumn.Text + ":" +
                                newQuickFilterWindow.textBoxFrom.Text + ":" +
                                newQuickFilterWindow.textBoxTo.Text;
                AddListQuickFilter(SelectedNode, Filter);
                LoadListItemsIntoTree(SelectedNode);

            }
            else if (Result == System.Windows.Forms.DialogResult.Cancel)
            {
                AddListQuickFilter(SelectedNode, "");
                LoadListItemsIntoTree(SelectedNode);
            }


        }


        private void AddListQuickFilter(TreeNode ListItemsNode, string Filter)
        {
            TreeNode ListNode = ListItemsNode.Parent;
            DataRow SelectedListItem = (DataRow)ListNode.Tag;
            SelectedListItem["System:ItemsFilter"] = Filter;
            //Reset the items if any
            //TODO: You might want to dispose the previous datatable assicated with items node to avoid memory leak
            if (string.IsNullOrEmpty(Filter))
                ListItemsNode.Text = "Items";
            else
                ListItemsNode.Text = "Items(Filtered)";
            ListItemsNode.Tag = new DataTable("ListItems");
        }
        private string GetListQuickFilter(TreeNode ListItemsNode)
        {
            TreeNode ListNode = ListItemsNode.Parent;
            DataRow SelectedListItem = (DataRow)ListNode.Tag;
            return SelectedListItem["System:ItemsFilter"].ToString();
        }

        private void checkBoxUseDefaultCredentials_CheckedChanged(object sender, EventArgs e)
        {
            txtDomain.Enabled = txtPassword.Enabled = txtUserName.Enabled = !(checkBoxUseDefaultCredentials.Checked);
        }

        private string GetSelectedNodePropertyValue(string PropertyName)
        {
          return GetPropertyValue(trvLists.SelectedNode,PropertyName);
        }
        private string GetPropertyValue(TreeNode Node, string PropertyName)
        {
            string PropertyValue = null;
            if (Node != null &&
                Node.Tag.GetType() == typeof(DataRow))
            {
                DataRow CurrentData = Node.Tag as DataRow;
                if (CurrentData.Table.Columns.Contains(PropertyName))
                {
                    return CurrentData[PropertyName].ToString();
                }
            }
            return PropertyValue;
        }
        private void deleteFieldToolStripMenuItem_Click(object sender, EventArgs e)
        {

            List<string> Columns = new List<string>(1);
            string ListId = "";
            string ListVersion = "";
            if (trvLists.SelectedNode != null)
            {          
                //Get Field Name
                string FieldName = GetSelectedNodePropertyValue("InternalName");
                string CanBeDelete = GetSelectedNodePropertyValue("CanBeDeleted");
                if (string.IsNullOrEmpty(FieldName) || 
                    string.IsNullOrEmpty(CanBeDelete)) return;
                if (CanBeDelete == "False")
                {
                    MessageBox.Show(ErrorHandler.GetFriendlyErrorMessage("CannotBeDeleted"),
                                   "Delete Field", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                
                Columns.Add(FieldName);

                //Load list properties
                TreeNode ParentListNode = trvLists.SelectedNode.Parent.Parent;
                ListId = GetPropertyValue(ParentListNode, "ID");
                ListVersion = GetPropertyValue(ParentListNode, "Version");
               
                _spWSWR.DeleteListFields(ListId, ListVersion, Columns);

                trvLists.Nodes.Remove(trvLists.SelectedNode);

            }
        }

        private void comboBoxSiteUrl_SelectionChangeCommitted(object sender, EventArgs e)
        {
            //Update SharePoint connections text boxes with the relevant info if found
            try
            {
                //Find the SharePoint Connection
                DataRow ConnectionRecord = GetSavedSharePointConnection(comboBoxSiteUrl.SelectedValue.ToString());
                if (ConnectionRecord != null)
                {
                    string Domain = ConnectionRecord["Domain"].ToString();
                    string Password = ConnectionRecord["Password"].ToString();
                    string UserName = ConnectionRecord["UserName"].ToString();

                    txtDomain.Text = string.IsNullOrEmpty(Domain)? "" : Security.DecryptStringAES(ConnectionRecord["Domain"].ToString(), Security.GetUniqueKey());
                    //Decrypt he password
                    string DcPassword = string.IsNullOrEmpty(Password) ? "" : Security.DecryptStringAES(ConnectionRecord["Password"].ToString(), Security.GetUniqueKey());
                    txtPassword.Text = DcPassword;
                    txtUserName.Text = string.IsNullOrEmpty(UserName) ? "" : Security.DecryptStringAES(ConnectionRecord["UserName"].ToString(), Security.GetUniqueKey());
                    checkBoxRememberCredentials.Checked = true;
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show("Error loading saved connections. Error: "+Ex.Message);
            }
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!ExitApplicationAndSave()) e.Cancel = true;
        }

        private void lastModifiedDateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.UseWaitCursor = true;
            string Header = "Index,Site Url,Site Title,Last Modified Date";
            saveFileDialogMain.Filter = "Comma Separated File|*.csv|All Files|*.*";
            if (saveFileDialogMain.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                DataTable Data = null;
                CollectSiteData("LastModified", false, trvLists.Nodes[0], ref Data);

                StreamWriter SR = new StreamWriter(saveFileDialogMain.FileName);
                SR.WriteLine(Header);
                foreach (DataRow record in Data.Rows)
                {
                    SR.WriteLine("{0},{1},{2},{3}", record["I"], record["Url"], record["Title"], record["LastModified"]);
                }
                SR.Close();
                this.UseWaitCursor = false;
                MessageBox.Show("The Report has been created successfully", "SharePoint Manager", MessageBoxButtons.OK);
            }
            this.UseWaitCursor = false;
        }
        private void CollectSiteData(string PropertyName, bool LoadedObjectsOnly, TreeNode Source, ref DataTable Data)
        {
            if (Data == null)
            {
                Data = new DataTable(PropertyName + "s");
                Data.Columns.Add("I");
                Data.Columns.Add("Url");
                Data.Columns.Add("Title");
                Data.Columns.Add(PropertyName);
            }
            DataRow CurrentNode = Source.Tag as DataRow;
            if (Source.Nodes["SubSites"] != null)
            {
                foreach (TreeNode subsite in Source.Nodes["SubSites"].Nodes)
                {
                    CollectSiteData(PropertyName, LoadedObjectsOnly, subsite, ref Data);
                }
            }
            else if(!LoadedObjectsOnly) //load all tree objects if not loaded
            {
                if (CurrentNode.Table.TableName == "Sites")
                {
                    //Load the node data
                    LoadSite(false, CurrentNode["Url"].ToString(), Source, false,false);
                    //Reload Properties
                    LoadPropertiesPage(CurrentNode);

                    if (Source.Nodes["SubSites"] != null)
                    {
                        foreach (TreeNode subsite in Source.Nodes["SubSites"].Nodes)
                        {
                            CollectSiteData(PropertyName, LoadedObjectsOnly, subsite, ref Data);
                        }
                    }
                }
            }
            DataRow newRecord = Data.NewRow();
            newRecord["I"] = Data.Rows.Count + 1;
            newRecord["Url"] = CurrentNode["Url"];
            newRecord["Title"] = CurrentNode["Title"];
            newRecord[PropertyName] = CurrentNode[PropertyName];
            Data.Rows.Add(newRecord);
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        


    }
    public class TrustAllCertificatePolicy : System.Net.ICertificatePolicy
    {
        public TrustAllCertificatePolicy() { }
        public bool CheckValidationResult(ServicePoint sp,
            X509Certificate cert,
            WebRequest req,
            int problem)
        {
            return true;
        }
    }

}
